import { ethers } from "hardhat";
import fs from "fs";
import path from "path";
import { artifacts } from "hardhat";

async function main() {
  const [deployer] = await ethers.getSigners();

  // 部署 Mock USDC 合约
  const USDC = await ethers.getContractFactory("MockUSDC");
  const usdc = await USDC.deploy();
  await usdc.waitForDeployment();
  console.log("MockUSDC deployed to:", await usdc.getAddress());

  // mint 初始代币给部署者
  // const mintAmount = ethers.parseUnits("1000000", 6); // 6位精度
  // await usdc.mint(deployer.address, mintAmount);
  // 3. 为所有20个测试账户铸造 USDC
  const accounts = await ethers.getSigners();
  const amount = ethers.parseUnits("10000", 6); // 10000 USDC（6位小数）
  for (let i = 0; i < 5; i++) { // 给前5个账户分配
    await usdc.mint(accounts[i].address, amount);
    console.log(`Minted 10000 USDC to ${accounts[i].address}`);
  }

  // 部署 MiniVault 合约
  const Vault = await ethers.getContractFactory("MiniVault");
  const vault = await Vault.deploy(await usdc.getAddress(),deployer.address);
  await vault.waitForDeployment();
  console.log("MiniVault deployed to:", await vault.getAddress());
  const balance = await usdc.balanceOf(deployer.address);//打印余额
  console.log("Deployer USDC Balance:", ethers.formatUnits(balance, 6));

  const abiDir = path.join(__dirname, "..", "frontend", "abis");
  fs.mkdirSync(abiDir, { recursive: true });

  const mockUSDCArtifact = await artifacts.readArtifact("MockUSDC");
  const miniVaultArtifact = await artifacts.readArtifact("MiniVault");

  fs.writeFileSync(
    path.join(abiDir, "MockUSDC.json"),
    JSON.stringify(mockUSDCArtifact, null, 2)
  );

  fs.writeFileSync(
    path.join(abiDir, "MiniVault.json"),
    JSON.stringify(miniVaultArtifact, null, 2)
  );

  const addresses = {
    MockUSDC: await usdc.getAddress(),
    MiniVault: await vault.getAddress(),
  };

  const contractsPath = path.join(__dirname, '..', 'frontend', 'constants', 'contracts.json');
  fs.mkdirSync(path.dirname(contractsPath), { recursive: true });
  fs.writeFileSync(contractsPath, JSON.stringify(addresses, null, 2));
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});
